import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// 创建一个实例
const service = axios.create({
  // 基准路径 url = base url + request url
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时时间
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  }
)

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    const { success, message } = res.data
    if (success) {
      return res.data.data
    } else {
      Message.error(message)
      return Promise.reject(message)
    }
  }, err => {
    if (err.response.data.code === 10002) {
      store.commit('user/getout')
      router.push('/login')
    }
    Message.error(err.response.data.message)
    return Promise.reject(err.response.data.message)
  }
)

export default service
